package blog.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import blog.domain.Article;
import blog.domain.Comment;

@Transactional(propagation = Propagation.MANDATORY)
public class CommentDao {
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public List<Article> getTopTenArticle() {
		Query query = sessionFactory
				.getCurrentSession()
				.createQuery(
						"select c.article, count(*) as articleNum from Comment c group by c.article order by articleNum desc");
		query.setFirstResult(0);
		query.setMaxResults(2);
		List<Object[]> items = query.list();
		List<Article> articles = new ArrayList<Article>();
		for(Object[] item:items) {
			articles.add((Article)item[0]);
		}
		return articles;
	}

	@SuppressWarnings("unchecked")
	public List<Comment> getTopTenComment() {
		Query query = sessionFactory
				.getCurrentSession()
				.createQuery("from Comment order by date desc");
		query.setFirstResult(0);
		query.setMaxResults(10);
		return query.list();
	}
}
